// * <div id="app"> hello {{msgH}<h></h></div>
//
// 解析标签变成render
// render _c( 'div ',{id:app},_v( "hello'+_s(msg)),_C)*}
//

import { defaultTagRE } from "./parseAst";

//处理属性样式
function genPorps(attrs) {
  let str = "";
  for (let i = 0; i < attrs.length; i++) {
    let attr = attrs[i];
    //是否为行列样式 attr= {name:'style',value:"font-weight: 200;color: blanchedalmond;"} 变成 {style:{color:red}}
    if (attr.name === "style") {
      let obj = {};
      attr.value.split(";").forEach((item) => {
        let [key, val] = item.split(":");
        obj[key] = val;
      });
      attr.value = obj;
    }
    //拼接
    str += `${attr.name}:${JSON.stringify(attr.value)},`; //id:"app",style:{"font-weight":" 200","color":" blanchedalmond"},
  }
  return `{${str.slice(0, -1)}}`; //去除最后的逗号
}
//处理子集
function genchildren(ast) {
  let children = ast.children;
  if (children) {
    return children.map((child) => gen(child)).join(",");
  }
}
//1 元素 3 文本
function gen(node) {
  if (node.type === 1) {
    //是元素就递归
    return generate(node);
  } else {
    //获取文本
    let text = node.text;
    if (!defaultTagRE.test(text)) {
      return `_v(${JSON.stringify(text)})`;
    }
    let tokens = [];
    let lastindex = (defaultTagRE.lastIndex = 0); //重置为0 不然匹配不到 不能多次匹配
    let match;
    while ((match = defaultTagRE.exec(text))) {
      let index = match.index;
      if (index > lastindex) {//说明{{}}前有文字要给取下来 发现双括号的起始位置和上次发现双括号的结束位置比较
        tokens.push(JSON.stringify(text.slice(lastindex, index)));
      }
      tokens.push(`_s(${match[1]})`);//取双括号的里面内容
      lastindex = index + match[0].length; //看看{{msg}} 后面还有文本？
    }
    if (lastindex < text.length) {
      tokens.push(JSON.stringify(text.slice(lastindex)));
    }
    //最终返回出去的
    return `_v(${tokens.join("+")})`;
  }
}
export function generate(ast) {
  let children = genchildren(ast);
  let code = `_c('${ast.tag}',${
    ast.attrs.length ? `${genPorps(ast.attrs)}` : 'undefined'
  },${children ? `${children}` : ''})`;
  return code;
}
